package org.vectrics.recruiter.user.resume.email;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.user.PhoneNumber;
import org.vectrics.user.PhoneNumberSet;

public class DataExtractor {
	private transient Logger log = Logger.getLogger(this.getClass());
	private EmailedResumeInfo info = null;
	private ExtractedData data = new ExtractedData();
	
	public DataExtractor(EmailedResumeInfo info) {
		super();
		this.info = info;
	}

	
	public ExtractedData extract() {
		findNames();
		findPhoneNumbers();
		findEmailAddresses();
		findTests();
		return(data);
	}
	
	private void findTests() {
		log.debug("Check email subject");
		this.data.getTestList().clear();
		String subject = this.info.getEmailSubject();
		JobExtractor extractor = new JobExtractor();
		Set allExtractedJobs = new HashSet();
		Set jobsExtractedFromSubject = extractor.findTestsInText(info.getDomain(), subject);
		Set jobsExtractedFromCoverLetter = extractor.findTestsInText(info.getDomain(), subject);
		allExtractedJobs.addAll(jobsExtractedFromSubject);
		allExtractedJobs.addAll(jobsExtractedFromCoverLetter);
		this.data.getTestList().addAll(allExtractedJobs);
	}
	
	private void findNames() {
		String fromName = info.getFromEmailName();
		if ((fromName != null) && (fromName.length() > 2)) {
			data.getNames().add(new StringScore(fromName, 90));
		}
		
		
	}
	
	private void findPhoneNumbers() {
		Iterator iter = this.info.getAttachments().iterator();
		while (iter.hasNext()) {
			EmailedResumeAttachment attachment = (EmailedResumeAttachment)iter.next();
			String content = attachment.getDocument().getTextContent();
			WordExtractor wordExtractor = RecruitServiceLocator.getWordExtractor();
			WordList wordList = wordExtractor.getWordList(content);
			PhoneNumberExtractor phoneNumberExtractor = new PhoneNumberExtractorUS();
			PhoneNumberSet phoneNumbers = phoneNumberExtractor.findPhoneNumbersInText(wordList);
			Iterator phoneIter = phoneNumbers.iterator();
			while (phoneIter.hasNext()) {
				PhoneNumber phone = (PhoneNumber)phoneIter.next();
				data.getPhoneNumbers().add(phone.getFormattedNumber(), 80);
			}
		}
	}
	
	
	private void findEmailAddresses() {
		
	}
}
